﻿using System;
using System.Reflection;
using Model;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Tool.hbm2ddl;
using Environment = NHibernate.Cfg.Environment;

namespace DataTierTest
{
    class InMemoryDatabase : IDisposable
    {
        	private readonly Configuration _configuration;
	        private readonly ISessionFactory _sessionFactory;
            public ISession Session { get; private set; }
            public ISessionProvider<ISession> SessionProvider { get; private set; } 

            

	        public InMemoryDatabase(Assembly assemblyContainingMapping)
	        {
		        if (_configuration == null)
		        {
			        _configuration = new Configuration()
				        .SetProperty(Environment.ReleaseConnections,"on_close")
				        .SetProperty(Environment.Dialect, typeof (SQLiteDialect).AssemblyQualifiedName)
				        .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
                        .SetProperty(Environment.ConnectionString, "Data Source=:memory:;Version=3;New=True;")
				        .AddAssembly(assemblyContainingMapping);

			        _sessionFactory = _configuration.BuildSessionFactory();
		        }

		        Session = _sessionFactory.OpenSession();
                SessionProvider = new InMemorySessionProvider(Session);

		        new SchemaExport(_configuration).Execute(true,true,false,Session.Connection,null);
	        }

	        public void Dispose()
	        {
		        Session.Dispose();
	        }

            private class InMemorySessionProvider  : ISessionProvider<ISession>
            {
                public InMemorySessionProvider(ISession session)
                {
                    Session = session;
                }
                public ISession Session {get; private set; }
            }


        public void FlushAndClear()
        {
            Session.Flush();
            Session.Clear();
        }

            

    }
}
